package sbc.group1.lab1.mozartspaces;

import org.mozartspaces.core.Capi;
import org.mozartspaces.core.MzsCoreException;
import org.mozartspaces.core.RequestFuture;
import org.mozartspaces.core.TransactionReference;
import org.mozartspaces.core.util.Nothing;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

class FailedTransactionHandler implements Runnable {
    
    private static final Logger log = LoggerFactory.getLogger(FailedTransactionHandler.class);
    
    private final RequestFuture<Nothing> writeOp;
    private final RequestFuture<Nothing> commitOp;
    private final TransactionReference transaction;
    private final Capi capi;
    
    public FailedTransactionHandler(RequestFuture<Nothing> writeOp, 
            RequestFuture<Nothing> commitOp, 
            TransactionReference transaction, Capi capiForRollback) {
        this.writeOp=writeOp;
        this.commitOp=commitOp;
        this.transaction=transaction;
        this.capi = capiForRollback;
    }
    @Override
    public void run() {
        try {
            if (writeOp!=null) {
                writeOp.getResult();
            }
            log.trace("Write done.");
            commitOp.getResult();
            log.trace("Commited ", transaction);
        } catch (MzsCoreException e) {
            log.error("Transaction failed.",e);
            try {
                capi.rollbackTransaction(transaction);
            } catch (MzsCoreException e1) {
                log.error("Rollback failed.",e1);
            }
        } catch (InterruptedException e) {
            log.warn("Interrupted while waiting for RequestFuture<Nothing>");
        }
    }
    
}
